package com.nsapi.niceschoolapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nsapi.niceschoolapi.entity.Role;
import com.nsapi.niceschoolapi.entity.User;
import com.nsapi.niceschoolapi.mapper.RoleMapper;
import com.nsapi.niceschoolapi.service.RoleService;
import com.nsapi.niceschoolapi.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserService userService;

    // 查询全部角色
    @Override
    public List<Role> selectAll() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("del_flag", false);
        return baseMapper.selectList(wrapper);
    }

    // 注入用户
    @Override
    public List<Role> setUser(List<Role> roleList) {
        for (Role r : roleList) {
            if (StringUtils.isNotBlank(r.getCreateId())) {
                User u = userService.findUserById(r.getCreateId());
                r.setCreateUser(u);
            }
            if (StringUtils.isNotBlank(r.getUpdateId())) {
                User u = userService.findUserById(r.getUpdateId());
                r.setUpdateUser(u);
            }
        }
        return roleList;
    }

    // 查询角色民是否已存在
    @Override
    public int getRoleNameCount(String name) {
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("name", name);
        List<Role> roleList = baseMapper.selectList(roleQueryWrapper);
        return roleList.size();
    }

    // 添加角色
    @Override
    public Role saveRole(Role role) {
        baseMapper.insert(role);
        if(role.getMenuSet() != null && role.getMenuSet().size() > 0) {
            baseMapper.saveRoleMenus(role.getId(),role.getMenuSet());
        }
        return role;
    }

     // 删除角色
    @Override
    public int deleteRole(String id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public Role getRoleById(String id) {
        return baseMapper.selectRoleById(id);
    }

    @Override
    public void updateRole(Role role) {
        baseMapper.updateById(role);
        baseMapper.dropRoleMenus(role.getId());
        if(role.getMenuSet() != null && role.getMenuSet().size() > 0) {
            baseMapper.saveRoleMenus(role.getId(), role.getMenuSet());
        }
    }

}
